﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MedicalManagementSystem.Utils;

namespace MedicalManagementSystem.Models
{
    public partial class Address : IValidatable
    {
        public static Address GetByPK(int id)
        {
            return DbContext.Instance.Address.Where(address => address.id == id).FirstOrDefault();
        }

        public void LoadDistrict()
        {
            if (EntityState != System.Data.EntityState.Added && EntityState != System.Data.EntityState.Detached)
            {
                if(!DistrictReference.IsLoaded)
                {
                    this.DistrictReference.Load();
                }
            }
        }

        public void LoadPatient()
        {
            if (EntityState != System.Data.EntityState.Added && EntityState != System.Data.EntityState.Detached)
            {
                if (!PatientReference.IsLoaded)
                {
                    PatientReference.Load();
                }
            }
        }

        public Region Region
        {
            get
            {
                LoadDistrict();
                this.District.Load();
                return this.District.Region;
            }
        }

        public string Description
        {
            get
            {
                LoadDistrict();
                return string.Format("Область: {0}. Район:{1}. {2}", Region.Name, District.Name, FullAddress);
            }
        }

        public bool CheckBeforeSave()
        {
            return GetRuleViolations().Count() == 0;
        }

        public IEnumerable<IRuleViolation> GetRuleViolations()
        {
            if (string.IsNullOrWhiteSpace(FullAddress))
            {
                yield return new RuleViolation("Адресс не может быть  пустым", this, "FullAddress", FullAddress);
            }
        }
    }
}
